package com.market.dao.jpa;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.market.dao.PurchaseDao;
import com.market.domain.Purchase;
import com.market.domain.Purchase.STATUS;
import com.market.domain.PurchaseDetail;

@Repository("purchaseDao")
public class PurchaseDaoJpa extends GenericDaoJpa<Purchase, Long> implements
		PurchaseDao {
	public PurchaseDaoJpa() {
		super(Purchase.class);
	}

	public void remove(Purchase object) {
		if (super.findById(object.getId()) == null) {
			log.debug(this.getClass() + " Purchase with id " + object.getId()
					+ " is not found, can not be removed");

		} else {
			log.debug(this.getClass() + " Purchases with id " + object.getId()
					+ " is found, will be removed");
			super.removeById(object.getId());
		}

	}

	public List<PurchaseDetail> findPurchaseDetails(Purchase purchase) {
		String sql = "select purchasedetail.* from purchase_purchasedetail,purchasedetail "
				+ " where purchasedetail.id = purchase_purchasedetail.purchasedetails_id "
				+ " and purchase_purchasedetail.purchase_id = "
				+ purchase.getId();
		Query q = this.em.createNativeQuery(sql, PurchaseDetail.class);
		List<PurchaseDetail> details = q.getResultList();
		return details;
	}

	/**
	 * This method override save method in super class, the difference is new
	 * purchase have the procedure of generating puchaseNumber and saving it.
	 */
	public Purchase save(Purchase object) {
		Purchase purchase;
		if (object.getIsNew() == true) {
			object.setPurchasedDate(new Date());
			object.setNumber(String.valueOf(new Date().getTime())); // This act
																	// as a
																	// temporary
																	// order
																	// number
			purchase = super.persist(object);
			SimpleDateFormat formatter = new SimpleDateFormat("yyMMddEEE");
			String required = formatter.format(purchase.getRequiredDate());
			String number = required + "-" + purchase.getId();
			purchase.setNumber(number);
			object.setStatus(STATUS.PURCHASED);
			purchase = super.merge(purchase);
		} else {
			purchase = super.merge(object);
		}
		for (PurchaseDetail detail : purchase.getPurchaseDetails()) {
			detail.setIsNew(false);
		}
		return purchase;
	}

}
